<script setup lang='ts'>
import type { ElTreeV2 } from 'element-plus'
import type { VxePagerEvents } from 'vxe-table'

import { useDeleteSysUser, useGetDataSourceUserListByPage, useGetOrgDataSourceTree, useGetSysOrgDataSourceTree, useGetSysUserListByPage } from '@fl/api/man-api'
import { SearchForm, SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { getElementLabelLine } from 'element-tree-line'
import 'element-tree-line/dist/style.css'
import { cloneDeep } from 'lodash-es'
import { h } from 'vue'

import Add from './add.vue'
import Authorized from './authorized.vue'
import { WHCJSOURCE_DICT } from './constant'
import Show from './show.vue'

const ElementTreeLine = getElementLabelLine(h)

const { createConfirmModal } = useMessage()

const { path } = useRoute()

const { isPending, mutate } = useDeleteSysUser()

const showVisible = ref<boolean>(false)

const authorizedVisible = ref<boolean>(false)

const addVisible = ref<boolean>(false)

const showType = ref<'edit' | 'view'>('view')

const id = ref<any>('')

type Tree = {
    [key: string]: any
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTreeV2>>()

const defaultProps = {
    children: 'childs',
    label: 'orgName',
    value: 'orgCode',
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

function filterNode(value: string, data: Tree) {
    if (!value)
        return true
    return data.orgName.includes(value)
}

const isSetting = path.includes('personnel-setting') // 是否系统配置

const initialState = {
    xm: '',
}

const state = ref(cloneDeep(initialState))

const columns = [
    {
        label: '姓名',
        prop: 'xm',
        renderField: (_, onChange) => {
            return h(ElInput, {
                onChange,
                onKeydown: (event: any) => {
                    if (event.key === 'Enter') {
                        event.preventDefault()
                    }
                },
            })
        },
        valueType: 'Input',
    },
]

const gridOptions = reactive({
    columns: [
        { fixed: 'left', title: '序号', type: 'seq', width: 50 },
        { field: 'personxm', title: '姓名', width: 100 },
        { field: 'personsszzname', title: '所属组织', width: 100 },
        { field: 'persongwlb', title: '当前岗位', visible: !isSetting, width: 100 },
        { field: 'persongwmc', title: '当前职务', visible: !isSetting, width: 100 },
        { field: 'personrylx', title: '人员类型', visible: !isSetting, width: 100 },
        { field: 'personsjhm', title: '手机号码', width: 100 },
        { field: 'personxgr', title: '修改人', width: 100 },
        { field: 'personxgsj', minWidth: 100, title: '修改时间' },
        { field: 'whcjsourceName', title: '来源', visible: isSetting, width: 100 },
        { field: 'personryzt', title: '人员状态', width: 100 },
        { fixed: 'right', slots: { default: 'opreate' }, title: '操作', width: isSetting ? 320 : 100 },
    ],
    data: [{}],
    height: isSetting ? 500 : 700,
    rowConfig: {
        keyField: 'whcjpersonid',
    },
    showOverflow: true,
})

const initialPage = { currentPage: 1, pageSize: 15, total: 0 }

const tablePage = ref(cloneDeep(initialPage))

const { data: SourceTreeData, isLoading: SourceTreeLoading } = isSetting ? useGetSysOrgDataSourceTree() : useGetOrgDataSourceTree()

const bm = ref('')

const params = computed(() => {
    return {
        bm: bm.value,
        page: tablePage.value.currentPage,
        size: tablePage.value.pageSize,
        xm: state.value?.xm,
    }
})

const { data: UserListData, isLoading: UserListLoading } = isSetting ? useGetSysUserListByPage(params) : useGetDataSourceUserListByPage(params)

const tableData = computed(() => {
    if (UserListData.value) {
        const result = cloneDeep(UserListData.value?.records) || []
        result.forEach((item: any) => {
            if (item.whcjsource) {
                item.whcjsourceName = WHCJSOURCE_DICT[item.whcjsource]
            }
        })
        return result
    }
    return []
})

const treeData = computed(() => SourceTreeData.value ? cloneDeep(SourceTreeData.value) : [])

const loading = computed(() => SourceTreeLoading.value)

function handleNodeClick(data: Tree) {
    tablePage.value.currentPage = 1
    bm.value = data.orgCode
}

function search(val: any) {
    tablePage.value.currentPage = 1
    state.value = cloneDeep(val)
}

function reset() {
    tablePage.value.currentPage = 1
    state.value = initialState
}

const detailValue = ref()

function showDetail(row: any) {
    id.value = row.whcjpersonid
    detailValue.value = cloneDeep(row)
    showType.value = 'view'
    showVisible.value = true
}

function editDetail(row: any) {
    detailValue.value = cloneDeep(row)
    showType.value = 'edit'
    id.value = row.whcjpersonid
    showVisible.value = true
}

function showAuthorized(row: any) {
    detailValue.value = cloneDeep(row)
    id.value = row.whcjpersonid
    authorizedVisible.value = true
}

function deleteRow(row: any) {
    createConfirmModal({
        content: '是否确认删除?',
        onError: () => {
            ElMessage.info('取消删除')
        },
        onSuccess: () => {
            const params = {
                id: row.id,
                personbm: row.personbm,
            }
            mutate(params, {
                onSuccess: () => {
                    ElMessage.success('操作成功')
                },
            })
        },
    })
}

function showAdd() {
    id.value++
    addVisible.value = true
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

watchEffect(() => {
    if (UserListData.value) {
        tablePage.value.total = UserListData.value?.total ?? 0
    }
})

watchEffect(() => {
    if (SourceTreeData.value) {
        const orgCode = SourceTreeData.value?.[0]?.orgCode
        setTimeout(() => {
            treeRef.value?.setCurrentKey(orgCode)
            bm.value = orgCode
        }, 100)
    }
})

const asideWidth = ref<number>(300)

let isResizing = false
let startX = 0
let startWidth = 0

function startResizing(event: MouseEvent) {
    isResizing = true
    startX = event.clientX
    startWidth = asideWidth.value

    document.addEventListener('mousemove', resizeAside)
    document.addEventListener('mouseup', stopResizing)
}

function resizeAside(event: MouseEvent) {
    if (isResizing) {
        const newWidth = startWidth + (event.clientX - startX)
        asideWidth.value = newWidth < 300 ? 300 : newWidth > 500 ? 500 : newWidth // 设置最小宽度为 50px
    }
}

function stopResizing() {
    isResizing = false
    document.removeEventListener('mousemove', resizeAside)
    document.removeEventListener('mouseup', stopResizing)
}

onMounted(() => {
    document.addEventListener('mouseup', stopResizing)
})

onUnmounted(() => {
    document.removeEventListener('mouseup', stopResizing)
})
</script>

<template>
    <ElSkeleton v-if="loading"
                animated
    />

    <el-container v-else
                  class="h-800"
    >
        <el-aside class="p-10 mr-10 bg-#fff relative"
                  :style="{ width: `${asideWidth}px` }"
        >
            <div class="flex flex-col h-full">
                <el-input v-model="filterText"
                          placeholder="请输入关键字"
                          class="mb-10"
                          clearable
                />

                <ElTreeV2 ref="treeRef"
                          :data="treeData"
                          :props="defaultProps"
                          highlight-current
                          :filter-method="filterNode"
                          :expand-on-click-node="false"
                          :height="720"
                          @node-click="handleNodeClick"
                >
                    <template #default="{ node }">
                        <ElementTreeLine :node="node"
                                         :tree-data="treeData"
                                         :show-label-line="true"
                        >
                            <span :title="node.label"
                                  v-text="node.label"
                            />
                        </ElementTreeLine>
                    </template>
                </ElTreeV2>
            </div>

            <div class="resizer"
                 @mousedown="startResizing"
            />
        </el-aside>

        <el-main class="bg-#fff">
            <div class="flex flex-col gap-20 h-full">
                <div class="text-16 font-700">
                    人员列表
                </div>

                <SearchForm v-if="isSetting"
                            v-bind="state"
                            :columns="columns"
                            submit-text="查询"
                            class="mb-20"
                            @submit="search"
                            @reset="reset"
                />

                <div v-if="isSetting"
                     class="mb-20"
                >
                    <el-button type="primary"
                               @click="showAdd"
                    >
                        新增人员
                    </el-button>
                </div>

                <SearchTable v-bind="gridOptions"
                             v-model:pager="tablePage"
                             class="flex-1"
                             :loading="UserListLoading || isPending"
                             :data="tableData"
                             :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
                             @page-change="handlePageChange"
                >
                    <template #opreate="{ row }">
                        <el-button text
                                   @click="showDetail(row)"
                        >
                            详情
                        </el-button>

                        <template v-if="isSetting">
                            <el-button text
                                       @click="editDetail(row)"
                            >
                                编辑
                            </el-button>

                            <el-button text
                                       @click="showAuthorized(row)"
                            >
                                授权账号
                            </el-button>

                            <el-button v-if="row?.isAccredit === '0'"
                                       text
                                       @click="deleteRow(row)"
                            >
                                删除
                            </el-button>
                        </template>
                    </template>
                </SearchTable>

                <!-- <div class="bg-red flex-1 h-full" /> -->
            </div>
        </el-main>
    </el-container>

    <Show :key="id"
          v-model:visible="showVisible"
          v-model:id="id"
          v-model:showType="showType"
          v-model:detailValue="detailValue"
          v-model:treeData="treeData"
    />

    <Authorized v-if="isSetting"
                v-model:id="id"
                v-model:visible="authorizedVisible"
                v-model:detailValue="detailValue"
    />

    <Add v-if="isSetting"
         v-model:id="id"
         v-model:visible="addVisible"
         v-model:treeData="treeData"
         v-model:maxLength="tablePage.total"
    />
</template>

<style lang="scss" scoped>
.el-main {
    padding: 20px;
}

:deep(.el-card__body) {
    height: 100%;
}

.el-aside {
    overflow: hidden;
}

.resizer {
    position: absolute;
    top: 0;
    right: 0;
    width: 3px;
    height: 100%;
    cursor: ew-resize;
    background-color: rgb(0 0 0 / 20%);
}

:deep(.el-tree-node:last-child > .el-tree-node__content::before) {
    content: '';
    width: 0;
    height: 10000px;
    background-color: #e7e7e7;
    position: absolute;
    margin-left: -9px;
    bottom: 13px;
}
</style>
